#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>

#define SA struct sockaddr
#define PATHNAME "/tmp/unixudp"

void err_sys(const char *errmsg);

int main(void)
{
    int sockfd;
    struct sockaddr_un servaddr, cliaddr;
    char buf[BUFSIZ];
    ssize_t n;
    socklen_t len = sizeof(cliaddr);

    if ((sockfd = socket(AF_LOCAL, SOCK_DGRAM, 0)) == -1)
        err_sys("socket");

    bzero(&servaddr, sizeof(servaddr));
    unlink(PATHNAME);
    servaddr.sun_family = AF_LOCAL;
    strncpy(servaddr.sun_path, PATHNAME, sizeof(servaddr.sun_path) - 1);

    if (bind(sockfd, (SA *)&servaddr, sizeof(servaddr)) == -1)
        err_sys("bind");

    for(;;){
        n = recvfrom(sockfd, buf, sizeof(buf), 0, (SA *)&cliaddr, &len);
        if (n == -1)
            err_sys("recvfrom");
        else
            printf("%s\n", buf);

        if (sendto(sockfd, buf, n, 0, (SA *)&cliaddr, sizeof(cliaddr)) != n)
            err_sys("sendto");

    }
    exit(0);
}

void err_sys(const char *errmsg)
{
    perror(errmsg);
    exit(1);
}
